import { PrismaClient } from '@prisma/client';
import {
  registerDecorator,
  ValidationOptions,
  ValidationArguments,
} from 'class-validator';

/**
 * 
 * 注册判断表中是否已经存在用户,如果存在就抛出异常
 */

export function isNotExistRule(
  property: string,
  validationOptions?: ValidationOptions,
) {
  return function (object: Object, propertyName: string) {
    registerDecorator({
      name: 'isNotExistRule',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [property],
      options: validationOptions,
      validator: {
        async validate(value: any, args: ValidationArguments) {

          const prisma = new PrismaClient();
          const user = await prisma[property].findFirst({
            where: {
              [propertyName]: args.value,
            },
          });

          return !Boolean(user);
        },
      },
    });
  };
}
